<template>
	<view class="charts-box">
	  <qiun-data-charts 
		type="pie"
		:opts="chartOpts"
		:chartData="formatChartData"
		v-if="isDataReady"
	  />
	</view>
</template>
  
<script>
export default {
	name: 'PieChart',
	props: {
		// 图表数据
		data: {
			type: Array,
			required: true,
			default: () => []
		}
	},
	data() {
		return {
			isDataReady: false,
			// 图表配置
			chartOpts: {
				color: ["#6B8FF7","#91CB74","#8C8C8C","#FAC858","#F78686","#A8E7F7"],
				padding: [15, 15, 0, 15],
				enableScroll: false,
				dataLabel:false,
				extra: {
					pie: {
						border: false,
					}
				},
				legend: {
					show: true,
					position: 'bottom',
					float: 'left',
					padding: 10,
					margin: 5,
					itemGap: 10,
					fontSize: 13,
					lineHeight: 25,
					backgroundColor: 'rgba(0,0,0,0)',
					fontColor: '#666666',
					borderColor: 'rgba(0,0,0,0)',
					itemWidth: 20,
					itemHeight: 10,
					itemRadius: 5
				},
				tooltip: {
					showTitle: false,
					fontSize: 12,
					format: function(item) {
						return item.name + '：¥' + item.data.toFixed(2) + ' (' + (item.data * 100 / item.series.reduce((a, b) => a + b.data, 0)).toFixed(2) + '%)'
					}
				}
			}
		}
	},
	computed: {
		formatChartData() {
			if (!Array.isArray(this.data) || !this.data.length) {
				return { series: [] }
			}
			
			return {
				series: [{
					data: this.data
				}]
			}
		}
	},
	created() {
		this.checkDataReady();
	},
	watch: {
		data: {
			handler(newVal) {
				console.log('Data changed:', newVal);
				this.checkDataReady();
			},
			immediate: true,
			deep: true
		}
	},
	methods: {
		checkDataReady() {
			const hasData = Array.isArray(this.data) && this.data.length > 0;
			if (this.isDataReady !== hasData) {
				this.isDataReady = hasData;
				console.log('Data ready status:', this.isDataReady, 'Data:', this.data);
				
				if (this.isDataReady) {
					this.$nextTick(() => {
						this.$forceUpdate();
					});
				}
			}
		}
	}
}
</script>
  
<style scoped>
.charts-box {
	width: 100%;
	height: 300px;
}
</style>